<template>
	<!-- 使用 page-meta 组件配合阻止滚动穿透 ,page-meta一定作为页面的第一个节点-->
	<page-meta :page-style="'overflow:'+(show?'hidden':'visible')"></page-meta>

	<uni-nav-bar :height="nav_height+'px'" :statusBar="true" :fixed="true" :leftWidth="'200rpx'" :rightWidth="'200rpx'"
		:backgroundColor="'#fff'" @clickLeft="goBackHome">

		<block slot="left">
			<view class="firdge-switch-icon" style="display: inline-flex;align-items: center;padding-left: 10rpx;">
				<!-- <uni-icons type="arrow-left" size="30" color="#000"></uni-icons> -->
			</view>
		</block>

		<block slot="default">
			<view class="tab-list-view">
				<view class="item-box" v-for="(tab,index) in tabBars" :key="tab.id"
					:class="{'active' : tabIndex==index}" @tap="tabtap(index)">
					{{tab.name}}
				</view>
			</view>
		</block>
	</uni-nav-bar>

	<uni-popup ref="siftPopup" type="top" @change="changeSiftPop" :safeArea="false">
		<view class="sift-pop-content" :style="{'padding-top':statusbar_height+nav_height+'px'}">
			<view class="mode-list">
				<view class="mode-item" v-for="(item, index) in mode_list" :key="index" @click="selectMode(item.mode)">
					<view class="left" style="display: flex;">
						<iconfont :name="item.img" :size="30"></iconfont>
						<text style="padding-left: 20rpx;">{{item.value}}</text>
					</view>
					<uni-icons type="checkmarkempty" size="35" color="#165dff" v-if="mode==item.mode">
					</uni-icons>
				</view>
			</view>
		</view>
	</uni-popup>

	<uni-popup ref="photoPopup" type="bottom" @change="changePhotoPop" :safeArea="false">
		<view class="photo-pop-content">
			<view class="list-view">
				<view class="item-box" v-for="(item,index) in photo_type_list" :key="index"
					@click="selectPhotoType(index)">
					<iconfont :name="item.img" :size="30"></iconfont>
					<text style="padding-left: 20rpx;">{{item.text}}</text>
				</view>
			</view>
		</view>
	</uni-popup>

	<!-- <uni-drawer ref="showLeft" mode="left" :width="320">
		<view :style="{'padding-top':statusbar_height+'px'}"></view>
		<my-fridge-list :fridge_list="fridge_list" :defautl_fid="default_fridge.fid" :showInvite="false"
			:showArrow="false" :showDefaultTips="false" :showCheck="true" @switch="switchDefault">
		</my-fridge-list>
	</uni-drawer> -->

	<view class="home-container">
		<view class="detail-container">
			<!-- 搜索栏 -->
			<view class="search-box" style="position: sticky; top: 0;">
				<my-search :sift="tabIndex==0" :camera="tabIndex===1" :refresh="true" @camera="openPhotoModePop"
					@search="gotoSearch" @sift="openSiftModePop" @refresh="refreshPage">
				</my-search>

				<view class="sift-list" v-if="tabIndex===0&&mode=='time'||tabIndex===0&&mode=='location'">
					<view class="sift-item" :class="{'active' : modeIndex==index}"
						:style="{color:mode=='time'?item.color:'#306eff'}" v-for="(item,index) in sift_list"
						:key="index" @tap="modeActiveChanged(index)">
						<view style="display: flex; align-items: center;">
							<iconfont :name="item.img" :size="20" :color="item.color" v-if="mode=='time'"></iconfont>
							<text>{{item.text}}</text>
						</view>
					</view>
				</view>

			</view>
			<swiper :circular="false"
				:style="{height: tabIndex===0&&(mode=='time'||mode=='location')? wh-40+'px': wh+'px'}"
				:current="tabIndex" @change="tabChange">
				<swiper-item v-for=" (item, index) in 2" :key="index">
					<!-- 取出物品 -->
					<view class="take-view" v-if="index==0">
						<!-- 物品类别列表 -->
						<scroll-view class="left-scroll-view" scroll-y="true" style="height: 100%;" v-if="mode=='type'">
							<block v-for="(item, i) in sift_list" :key="i">
								<view :class="['left-scroll-view-item', i === cateIndex ? 'active' : '']"
									@click="cateActiveChanged(i)">
									{{sift_list[i]}}
								</view>
							</block>
						</scroll-view>

						<scroll-view scroll-y="true" :style="{'height':'100%','width':mode=='type'?'80%':'100%'}">
							<!-- 取出物资 -->

							<image src="../../static/empty_img/obj_empty.png" style="width: 100%;margin-top: 30%;"
								mode="widthFix" v-if="sift_obj_list.length==0"></image>

							<my-obj-list :fid="default_fridge.fid" :obj_list="sift_obj_list" @changePop="changePop">
							</my-obj-list>
						</scroll-view>
					</view>

					<!-- 存放物资 -->
					<my-store-list :wh="wh" :cate_list="cate_list" :fid="default_fridge.fid"
						:dataTree="fridge_structure" :detect_list="detect_list" @changePop="changePop" v-else>
					</my-store-list>

				</swiper-item>
			</swiper>
		</view>

	</view>
</template>

<script>
	// 导入自己封装的 mixin 模块
	import badgeMix from '@/mixins/tabbar-badge.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'

	export default {
		data() {
			return {
				show: false,
				// 胶囊位置属性
				menu_btn: {},
				statusbar_height: '',
				nav_height: '',
				search_height: 60,
				tabBars: [{
					id: 0,
					name: "取出"
				}, {
					id: 1,
					name: "存入"
				}],
				// 顶部索引
				tabIndex: 0,
				// 分类模式索引
				modeIndex: 0,
				// 物品类别索引
				cateIndex: 0,
				wh: 0,
				detect_list: [],
				mode_list: [{
					mode: 'all',
					value: '全部',
					img: 'all'
				}, {
					mode: 'type',
					value: '物品种类',
					img: 'type'
				}, {
					mode: 'location',
					value: '物品位置',
					img: 'location'
				}, {
					mode: 'time',
					value: '新鲜程度',
					img: 'fresh'
				}],
				mode: 'all',
				photo_type_list: [{
					text: '物品图片',
					img: 'addimg'
				}, {
					text: '购物清单',
					img: 'goodlist'
				}]
			}
		},
		// 将 badgeMix 混入到当前的页面中进行使用
		mixins: [badgeMix],
		computed: {
			// 2. 从 user 模块中导入需要的 token 字符串
			...mapState('user', ['token']),
			...mapState('fridge', ['default_fridge', 'fridge_structure']),
			...mapState('object', ['obj_list', 'cate_list']),
			sift_obj_list() {
				if (this.mode == 'all')
					return this.obj_list
				else if (this.mode == 'location') {
					const sift_condition = this.sift_list[this.modeIndex].text
					return this.obj_list.filter(x => {
						return x.location.substring(0, 3).trim() == sift_condition
					})
				} else if (this.mode == 'time') {
					return this.obj_list.filter(x => {
						if (this.modeIndex == 0)
							return x.shortestWarrantyTime <= 0
						else if (this.modeIndex == 1)
							return x.shortestWarrantyTime > 0 && x.shortestWarrantyTime < 7
						else return x.shortestWarrantyTime >= 7
					})
				} else {
					const sift_condition = this.sift_list[this.cateIndex]
					return this.obj_list.filter(x => {
						return x.classification == sift_condition
					})
				}

			},
			sift_list() {
				if (this.mode == 'location') {
					const list = []
					this.fridge_structure.forEach(x => {
						list.push({
							text: x.text
						})
					})
					return list
				} else if (this.mode == 'time') {
					return [{
						text: '过期',
						color: '#fc501c',
						img: 'danger'
					}, {
						text: '临期',
						color: '#f98700',
						img: 'warn'
					}, {
						text: '新鲜',
						color: '#96c0fd',
						img: 'fresh-circle'
					}]
				} else if (this.mode == 'type') {
					const list = []
					this.cate_list.forEach(x => {
						list.push(x.classification)
					})
					list.pop()
					return list
				} else return []
			}
		},

		watch: {
			token: {
				handler(newVal, oldVal) {
					// 退出登陆后，页面初始化
					if (newVal == '') {
						this.tabIndex = 0
						this.mode = 'all'
						this.modeIndex = 0
						this.cateIndex = 0
					}
				},
			},
			// tabIndex: {
			// 	handler(newVal, oldVal) {
			// 		// 防止在存入页面触发onShow时重置到取出页面
			// 		uni.setStorageSync('tabIndex', newVal)
			// 	},
			// }
		},

		onLoad() {
			this.menu_btn = uni.getMenuButtonBoundingClientRect()
			this.nav_height = this.menu_btn.height + 30
			// 获取当前系统的信息
			const sysInfo = uni.getSystemInfoSync()
			this.statusbar_height = sysInfo.statusBarHeight
			// 为 wh 窗口可用高度动态赋值，减去状态栏、导航栏、搜索栏的高度
			this.wh = sysInfo.windowHeight - this.nav_height - this.statusbar_height - this
				.search_height
		},

		onShow() {
			// 首页跳转的参数
			// this.tabIndex = uni.getStorageSync('tabIndex') || 0
			this.mode = uni.getStorageSync('mode') || 'all'
			this.modeIndex = uni.getStorageSync('modeIndex') || 0
		},

		methods: {
			...mapMutations('object', ['updateObjList', 'updateCateList']),

			// 刷新
			refreshPage() {
				if (this.tabIndex == 0) {
					uni.showLoading({
						mask: true,
						success: () => {
							this.updateObjList([])
							this.mode = 'all'
							this.modeIndex = 0
							uni.setStorageSync('mode', 'all')
							uni.setStorageSync('modeIndex', 0)
						}
					})
					setTimeout(() => {
						uni.$api.object.getAll()
						uni.hideLoading()
					}, 500)
				} else {
					uni.showLoading({
						mask: true,
						success: () => {
							this.updateCateList([])
						}
					})
					setTimeout(() => {
						uni.$api.object.getAllCateAndObj()
						uni.hideLoading()
					}, 500)
				}
			},

			// 跳转
			gotoSearch() {
				if (this.tabIndex === 0) {
					uni.navigateTo({
						url: '/pagesSub/pageSearch/obj_search/obj_search?flag=' + 'take'
					})
				} else {
					uni.navigateTo({
						url: '/pagesSub/pageSearch/obj_search/obj_search?flag=' + 'store'
					})
				}
			},
			goBackHome() {
				uni.navigateBack({
					delta: 1
				})
			},

			// 请求
			takePhoto(mode) {
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					// sourceType: ['album'], //从相册选择

					success: (chooseImageRes) => {
						uni.showLoading({
							title: '识别中',
						})

						// 压缩
						uni.compressImage({
							src: chooseImageRes.tempFilePaths[0],
							quality: 40,
							// compressedWidth: 500,

							// success: async (res) => {
							// 	const FormData = require('../../utils/formData/index.js')
							// 	let form = new FormData();
							// 	form.appendFile('image', res.tempFilePath)
							// 	const formData = form.getData()
							// 	const result = await uni.$api.object.detect(formData, mode)
							// 	this.detect_list = result
							// 	if (this.detect_list.length != 0)
							// 		uni.$showMsg('识别成功')
							// 	else uni.$showMsg('无法识别')
							// },

							success: (res) => {
								uni.uploadFile({
									url: mode === 0 ?
										uni.$uploadPath + '/objectDetection/detect' : uni
										.$uploadPath +
										'/objectDetection/detectByShoppingList',
									filePath: res.tempFilePath,
									name: 'image',
									header: {
										"token": this.token
									},
									formData: {},
									success: (res) => {
										if (res.statusCode !== 200)
											return uni.$showMsg('服务器繁忙')
										this.detect_list = []
										const {
											data: result
										} = JSON.parse(res.data)
										result.objectInfos.forEach(x => {
											x.object.imgSrc = uni
												.$staticResourcePath +
												x.object.imgSrc
											x.object.location = '1-1'
											x.object.num = x.detectNum
											this.detect_list.push(x.object)
										})
										if (this.detect_list.length != 0) {
											uni.$showMsg('识别成功')
											setTimeout(() => {
												this.detect_list = []
												uni.hideLoading();
											}, 1000);
										} else uni.$showMsg('无法识别')
									},
									fail: (res) => {
										uni.$showMsg('服务器域名出错')
										console.log(res.errMsg);
									}
								});
							}
						})

						setTimeout(() => {
							this.detect_list = []
							uni.hideLoading();
						}, 1000);
					}
				});
			},

			// 事件处理
			// 子传父，处理弹窗滑动穿透
			changePop(e) {
				this.show = e
			},
			//点击切换导航
			tabtap(index) {
				this.tabIndex = index;
				this.$refs.siftPopup.close()
				this.$refs.photoPopup.close()
			},
			//滑动切换导航
			tabChange(e) {
				this.tabIndex = e.detail.current
			},

			// 切换筛选模式
			openSiftModePop() {
				this.$refs.siftPopup.open()
			},
			changeSiftPop(e) {
				this.show = e.show
			},
			selectMode(mode) {
				this.mode = mode
				this.modeIndex = 0
				this.cateIndex = 0
				this.$refs.siftPopup.close()
			},
			// 位置和新鲜程度的切换
			modeActiveChanged(index) {
				this.modeIndex = index
			},
			// 物品类别的切换
			cateActiveChanged(index) {
				this.cateIndex = index
			},

			// 选择识图模式
			openPhotoModePop() {
				this.$refs.photoPopup.open()
			},
			changePhotoPop(e) {
				this.show = e.show
			},
			selectPhotoType(index) {
				if (index == 0)
					this.takePhoto(0)
				else {
					this.takePhoto(1)
				}
				this.$refs.photoPopup.close()
			}
		},
	}
</script>
<style lang="scss">
	.tab-list-view {
		color: #000;
		font-weight: bold;
		display: flex;
		align-items: center;
		font-size: 18px;
		justify-content: space-evenly;
		flex: 1;
		padding-bottom: 10rpx;

		.item-box {
			display: inline-flex;

			&.active {
				color: #10aeff;
				border-bottom: 6rpx solid #10aeff;
			}
		}
	}

	.home-container {
		display: flex;
		flex-direction: column;

		.detail-container {
			// 防止滑动穿透
			position: fixed;
			left: 0;
			right: 0;

			.search-box {
				.sift-list {
					height: 40px;
					display: flex;
					align-items: center;
					background-color: #fff;
					justify-content: space-around;
					width: 100%;

					.sift-item {
						display: flex;
						font-size: 40rpx;
						height: 100%;
						font-weight: 600;
						border-right: 1px solid #e5e6eb;
						width: 100%;
						justify-content: center;

						&.active {
							border-bottom: 3px solid #2979FF;
						}
					}
				}
			}

			.take-view {
				height: 100%;
				display: flex;

				.left-scroll-view {
					width: 20%;

					.left-scroll-view-item {
						line-height: 120rpx;
						background-color: #f2f3f5;
						text-align: center;
						font-size: 30rpx;

						// 激活项的样式
						&.active {
							background-color: #fff;
							color: #007AFF;
							position: relative;

							// 渲染激活项左侧的指示边线
							&::before {
								content: ' ';
								display: block;
								width: 10rpx;
								height: 60rpx;
								background-color: #007AFF;
								position: absolute;
								left: 0;
								top: 50%;
								transform: translateY(-50%);
							}
						}
					}
				}
			}
		}
	}

	.sift-pop-content {
		display: flex;
		flex-direction: column;
		background-color: #fff;
		border-radius: 0 0 20rpx 20rpx;
		align-items: center;
		padding-bottom: 20rpx;

		.mode-list {
			display: flex;
			flex-direction: column;
			width: 100%;
			align-items: center;

			.mode-item {
				display: flex;
				width: 90%;
				font-size: 40rpx;
				padding: 20rpx 0;
				border-bottom: 1px solid #d8d8d8;
				align-items: center;
				justify-content: space-between;
			}
		}
	}

	.photo-pop-content {
		display: flex;
		flex-direction: column;
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		align-items: center;

		.list-view {
			display: flex;
			flex-direction: column;
			width: 100%;
			align-items: center;

			.item-box {
				display: flex;
				width: 90%;
				font-size: 40rpx;
				padding: 20rpx 0;
				border-bottom: 1px solid #d8d8d8;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>